import java.util.Deque;
import java.util.LinkedList;
/**
* @author xnl
* @Description:
* @date: 2022/6/22 21:35
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode treeNode = new TreeNode(2, new TreeNode(1), new TreeNode(3));
System.out.println(solution.findBottomLeftValue(treeNode));
}
int n = 0;
int res = 0;
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return res;
}
/**
* 深度优先遍历
* @param root
* @param height
*/
private void dfs(TreeNode root, int height){
if (root == null){
return;
}
height++;
dfs(root.left, height);
dfs(root.right, height);
if (height > n){
n = height;
res = root.val;
}
}
/**
* 广度优先遍历
* @param root
*
*/
private int findBottomLeftValue2(TreeNode root){
int res = 0;
Deque<TreeNode> stack = new LinkedList<>();
stack.offer(root);
while (!stack.isEmpty()){
TreeNode temp = stack.poll();
if (temp.right != null){
stack.offer(temp.right);
}
if (temp.left != null){
stack.offer(temp.left);
}
res = temp.val;
}
return res;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
力扣:513. 找树左下角的值
于 2022-06-22 22:05:51 首次发布