LeetCode:513.找二叉树左下角的值
问题描述
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层最左边 节点的值。
假设二叉树中至少有一个节点。
解题思路
叶子节点它的深底一定是最大的,可能会出现多个深度相同且是最大的节点,只有左边的那个节点才符号,所有在处理时我们要优先处理左节点。
代码实现
public class Solution {
	int maxDepth=0;
	int res;
	public int findBottomLeftValue(TreeNode root) {
		res = root.val;
		findBottomLeafValue(root,0);
		return res;
	}
	public void findBottomLeaftValue(TreeNode root, int depth) {
		if (root.left == null && root.right == null) {
			if (depth >maxDepth) {
				maxDepth = depth;
				res = root.val;
			}
		}
		if (root.left != null) {
            findBottomLeftValue(root.left,depth+1);
        }
        if (root.right != null) {
            findBottomLeftValue(root.right,depth+1);
        }
		return;
	} 
}
实现细节
在只有一个节点的情况时,执行有两个形参数的方法时,直接返回,所以我们要在调用之前将,root.val赋值给res。
因为要取深度最大最左边的值(可能会出现多个深度相同的值),没有对中间节点的操作,三种遍历方法都在左子树比右子树先访问,三种遍历方法都可以。只有当前结点比最大深度更大时才会去更新maxDepth和res,如果相同时也去更新那得出的结果将是最右边的值。

                
            
        
浙公网安备 33010602011771号